import sys
import os
import re

from importlib.machinery import SourceFileLoader

thisDir = os.path.split(os.path.realpath(__file__))[0]

from GeneralServerInitializer import GeneralServerInitializer

import logging
logger = logging.getLogger(__name__)

class EJOServerInitializer(GeneralServerInitializer):
    def __init__(self):
        logger.debug("[EJOServerInitializer.EJOServerInitializer]")
        super().__init__()
        self.__modules = (
            ("EJOApiInitializer", os.path.join(thisDir, "..", "api", "EJOApiInitializer.py")),
            ("EJOUiInitializer", os.path.join(thisDir, "..", "ui", "EJOUiInitializer.py")),
            ("EJODbEngine", os.path.join(thisDir, "..", "db", "EJODbEngine.py")),
            None # Used here to make sure it is always two-dimensional data structure
        )

    def Initialize(self):
        logger.debug("[EJOServerInitializer.Initialize]")
        for i in self.__modules:
            if i and not self.__initImpl(i):
                return False
        return True

    def __initImpl(self, attr):
        name = attr[0]
        path = attr[1]
        try:
            initializerModule = SourceFileLoader(name, path).load_module()
            obj = getattr(initializerModule, name)
        except Exception as e:
            logger.error(f"Exception on load intializer: {name}")
            logger.error(e)
            return False
        if not obj:
            logger.error(f"Failed to get intializer: {name}")
            return False
        return obj().Initialize()
